/**
 * Module dependencies.
 */

var express = require('express'),
    routes = require('./routes'),
    webapp=require('./routes/webapp')
    http = require('http'),
    path = require('path'),
    flash=require('connect-flash'),
    ejs = require('ejs'),
    config=require('./config'),
    MongoStore = require('connect-mongo')(express),
    // settings = require('./settings'),
    app = express();

app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(flash());
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.urlencoded());
app.use(express.bodyParser({keepExtensions:true,uploadDir:'./public/images/upload'}));
//app.use(express.bodyParser())
app.use(express.methodOverride());
app.use(express.cookieParser());//cookie解析中间件
app.use(express.session({       //提供会话支持
    secret:config.cookieSecret,
    cookie:{maxAge:1000*60*60*10},//10个小时
    store:new MongoStore({
        db:config.db
    })
}))
app.use(function(req,res,next){       //注册全局变量
    var err = req.flash('error');
    var success = req.flash('success');
    res.locals.user = req.session.user;
    res.locals.error= err.length ? err : null;
    res.locals.success = success.length ? success : null;
    next();
});
app.use(function(req,res,next){
     var url=req.path;
     console.log(url);
     if(url.indexOf('webapp')<0){
         var reg=url.indexOf('.')<0&&url!='/'&&!req.session.user;
         if(reg){
             //req.flash('error','你没有登陆，不能操作');
             return res.redirect("/");
         }
     }else{
//         res.setHeader("Access-Control-Allow-Origin", "*");
//         res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
//         res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
     }
     next();
})

app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));


// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

routes(app);
webapp(app);

http.createServer(app).listen(3000);